﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.IO;

namespace DATN.mds.ContactManagement
{
    public partial class IndexCM : System.Web.UI.Page
    {
        private string cnnString;
        SqlConnection cnn;
        SqlCommand cmd;
        protected int currentPageNumber = 1;
        private int PAGE_SIZE = 15;

        protected void Page_Load(object sender, EventArgs e)
        {
                if (Session["Us_Id"] != null)
                {
                        //Bind data vào GridView
                        BindData();
                        Sex.Visible = false;
                        Name.Visible = false;
                        Birthday.Visible = false;
                        Phone.Visible = false;
                        Mail.Visible = false;
                        Address.Visible = false;
                        Married.Visible = false;
                        Job.Visible = false;
                        Company.Visible = false;
                        Salary.Visible = false;
                        Habit.Visible = false;
                        //Tạo note:
                        Session["Remind"] = null;
                }
                else {
                    Response.Redirect("../Account/Login.aspx");
                }
        }

        private void BindData()
        {
           int us_id = Convert.ToInt16(Session["Us_Id"].ToString());
            try
            {
                cnnString = ConfigurationManager.ConnectionStrings["DATNconnection"].ToString();
                SqlConnection myConnection = new SqlConnection(cnnString);

                SqlCommand myCommand = new SqlCommand("usp_GetCustomer", myConnection);
                myCommand.CommandType = CommandType.StoredProcedure;

                myCommand.Parameters.AddWithValue("@us_id", us_id);
                myCommand.Parameters.AddWithValue("@startRowIndex", currentPageNumber);
                myCommand.Parameters.AddWithValue("@maximumRows", PAGE_SIZE);
                myCommand.Parameters.Add("@totalRows", SqlDbType.Int);
                myCommand.Parameters["@totalRows"].Direction = ParameterDirection.Output;

                SqlDataAdapter ad = new SqlDataAdapter(myCommand);

                DataSet ds = new DataSet();
                ad.Fill(ds);

                Grd_SearchTrend.DataSource = ds;
                Grd_SearchTrend.DataBind();

                if (ds.Tables[0].Rows.Count == 0)
                {
                    Response.Redirect("../mds.UserInterface/InternalIndex.aspx");
                }
                else
                {
                    // get the total rows 
                    double totalRows = (int)myCommand.Parameters["@totalRows"].Value;

                    lblTotalPages.Text = CalculateTotalPages(totalRows).ToString();

                    lblCurrentPage.Text = currentPageNumber.ToString();

                    if (currentPageNumber == 1)
                    {
                        Btn_Previous.Enabled = false;

                        if (Int32.Parse(lblTotalPages.Text) > 1)
                        {
                            Btn_Next.Enabled = true;
                        }
                        else
                        {
                            Btn_Next.Enabled = false;
                        }
                    }
                    else
                    {
                        Btn_Previous.Enabled = true;

                        if (currentPageNumber == Int32.Parse(lblTotalPages.Text))
                        {
                            Btn_Next.Enabled = false;
                        }
                        else
                        {
                            Btn_Next.Enabled = true;
                        }
                    }
                }
            }
            catch(Exception ex)
            {
                Response.Write("trang load databind: " + ex);
            }

        }

        private int CalculateTotalPages(double totalRows)
        {
            int totalPages = (int)Math.Ceiling(totalRows / PAGE_SIZE);
            return totalPages;
        }

        // This method will handle the navigation/ paging index
        protected void ChangePage(object sender, CommandEventArgs e)
        {

            switch (e.CommandName)
            {
                case "Previous":
                    currentPageNumber = Int32.Parse(lblCurrentPage.Text) - 1;
                    break;

                case "Next":
                    currentPageNumber = Int32.Parse(lblCurrentPage.Text) + 1;
                    break;
            }

            BindData();
        }

        //Tạo mới Contact: Redirect sang trang Create Contact
        protected void bt_CreateCM_Click(object sender, EventArgs e)
        {
            Response.Redirect("/mds.ContactManagement/CreateCM.aspx");
            Session["Remind"] = null;
        }
 
        int noNumber = 0;
        //Access RowDataBound
        protected void Grd_ContactAll_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
              DataRowView row = e.Row.DataItem as DataRowView;

             // Hiển thị cho column Giới Tính
              Label Lb_Sex = e.Row.FindControl("Lb_Sex") as Label;
              if (Lb_Sex != null)
              {
                  if (row["Sex"].ToString() == "1")
                  {
                      Lb_Sex.Text = "Nam";
                  }
                  if (row["Sex"].ToString() == "2")
                  {
                      Lb_Sex.Text = "Nữ";
                  }
                  if (row["Sex"].ToString() == "3")
                  {
                      Lb_Sex.Text = "Khác";
                  }
              }

              // Hiển Thị khi click vào Delete
              if (e.Row.RowType == DataControlRowType.DataRow)
              {
                  LinkButton l = (LinkButton)e.Row.FindControl("LinkButton1");
                  l.Attributes.Add("onclick", "javascript:return " +
                  "confirm('Bạn muốn XÓA nội dung trong cột này! - " +
                  " Tên Danh bạ là: " + DataBinder.Eval(e.Row.DataItem, "FirstName") + "')");

                  LinkButton l2 = (LinkButton)e.Row.FindControl("LinkButton2");
                  l2.Attributes.Add("onclick", "javascript:return " +
                  "confirm('Bạn muốn SỬA nội dung trong cột này! - " +
                  " Tên Danh bạ là: " + DataBinder.Eval(e.Row.DataItem, "FirstName") + "')");
              }

              if (e.Row.DataItemIndex == -1)
                  return;

              e.Row.Attributes.Add("onMouseOver","this.style.cursor='hand';");
              if ((e.Row.RowIndex %2)==0)
              {
                  e.Row.Attributes.Add("onmouseover", "this.style.backgroundColor='#aafdaa'");
                  e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor='#b4cbd5'");
              }
              else
              {
                  e.Row.Attributes.Add("onmouseover", "this.style.backgroundColor='#aafdaa'");
                  e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor='#FFFFFF'");
              }

              //e.Row.Attributes.Add("onclick", "javascript:return " + "confirmation()");
              //e.Row.Attributes.Add("onclick", "javascript:return " +
              //     "alert('Khách Hàng: " + DataBinder.Eval(e.Row.DataItem, "FirstName") + 
              //     " Số điện thoại: " + DataBinder.Eval(e.Row.DataItem, "Phone") +
              //     " Địa Chỉ Mail: " + DataBinder.Eval(e.Row.DataItem, "Mail") + "')");
            }
        }

        protected void GridView1_RowCommand(object sender,GridViewCommandEventArgs e)
        {
            if (e.CommandName == "Delete")
            {
                // get the categoryID of the clicked row
                try
                {
                    int Cus_Id = Convert.ToInt32(e.CommandArgument);
                    // Create New Session And Redirect to delete page
                    Session["Cus_Id"] = Cus_Id.ToString();
                    Response.Redirect("/mds.ContactManagement/DeleteCM.aspx");
                }catch(Exception ex)
                {
                    Response.Write(ex);
                }
            }
            if (e.CommandName == "Edit")
            {
                // get the categoryID of the clicked row
                try
                {
                    int Cus_Id = Convert.ToInt32(e.CommandArgument);
                    // Create New Session And Redirect to delete page
                    Session["Cus_Id"] = Cus_Id.ToString();
                    Response.Redirect("/mds.ContactManagement/EditCM.aspx");
                }
                catch (Exception ex)
                {
                    Response.Write(ex);
                }
            }

            if (e.CommandName == "Mail")
            {
                // get the categoryID of the clicked row
                try
                {
                    int Cus_Id = Convert.ToInt32(e.CommandArgument);
                    // Create New Session And Redirect to delete page
                    Session["Cus_Id"] = Cus_Id.ToString();
                    Response.Redirect("../mds.MailManagement/SendMailList.aspx");
                }
                catch (Exception ex)
                {

                    Response.Write(ex);
                }
            }

            if (e.CommandName == "Xem")
            {
                // get the categoryID of the clicked row
                try
                {
                    int Cus_Id = Convert.ToInt32(e.CommandArgument);
                    BindDataXem(Cus_Id);
                }
                catch (Exception ex)
                {
                    Response.Write(ex);
                }
            }
        }

        //Bind Data vào Lable
        protected void BindDataXem(int Cus_Id)
        {
            Sex.Visible = true;
            Name.Visible = true;
            Birthday.Visible = true;
            Phone.Visible = true;
            Mail.Visible = true;
            Address.Visible = true;
            Married.Visible = true;
            Job.Visible = true;
            Company.Visible = true;
            Salary.Visible = true;
            Habit.Visible = true;

            try
            {
                cnnString = ConfigurationManager.ConnectionStrings["DATNconnection"].ToString();
                cnn = new SqlConnection(cnnString);
                cnn.Open();

                String queryString = "SELECT * FROM [dbo].[Customers]  WHERE (([Cus_Id] = @Cus_Id))";
                cmd = new SqlCommand(queryString, cnn);
                cmd.Parameters.Add("@Cus_Id", SqlDbType.Int);
                cmd.Parameters["@Cus_Id"].Value = Cus_Id;

                SqlDataReader reader = cmd.ExecuteReader();
                DateTime birth = new DateTime();
                while (reader.Read())
                {
                    Name.Text = "<b>Họ và Tên: </b>" + reader["LastName"].ToString()+" "+ reader["FirstName"].ToString();
                    if (reader["Sex"].ToString() == "1")
                    {
                        Sex.Text = "<b>Giới Tính: </b> Nam";
                    }
                    else if (reader["Sex"].ToString() == "2")
                    {
                        Sex.Text = "<b>Giới Tính: </b> Nữ";
                    }
                    else if (reader["Sex"].ToString() == "3")
                    {
                        Sex.Text = "<b>Giới Tính: </b> Khác";
                    }
                    birth = Convert.ToDateTime(reader["Birthday"]);
                    Birthday.Text ="<b>Sinh Nhật:</b> " + birth.ToString("dd/MM/yyyy");

                    Phone.Text = "<b>Số Điện Thoại: </b>" + reader["Phone"].ToString();
                    Mail.Text = "<b>Địa Chỉ Thư: </b>" + reader["Mail"].ToString();
                    Address.Text = "<b>Địa Điểm: </b>" + reader["Address"].ToString() + ", <b>Thành phố: </b>"+ reader["City"].ToString();

                    Company.Text = "<b>Công Ty: </b>" + reader["Company"].ToString();
                    if (reader["MaritalStatus"].ToString() == "1")
                    {
                        Married.Text = "<b>Tình Trạng Hôn Nhân: </b> Độc Thân";
                    }
                    else if (reader["MaritalStatus"].ToString() == "2")
                    {
                        Married.Text = "<b>Tình Trạng Hôn Nhân: </b> Đã Kết Hôn";
                    }
                    else if (reader["MaritalStatus"].ToString() == "3")
                    {
                        Married.Text = "<b>Tình Trạng Hôn Nhân: </b> Khác";
                    }

                    Salary.Text = "<b>Mức Lương: </b> " + reader["Salary"].ToString() + "(Triệu VND)";
                    
                    Habit.Text = "<b>Thói Quen: </b>" + reader["Habit"].ToString();

                    if (reader["Job"].ToString() == "1")
                    {
                        Job.Text = "<b>Công Việc: </b> Kinh Doanh";
                    }
                    else if (reader["Job"].ToString() == "2")
                    {
                        Job.Text = "<b>Công Việc: </b> Văn Phòng";
                    }
                    else if (reader["Job"].ToString() == "3")
                    {
                        Job.Text = "<b>Công Việc: </b> Kĩ Thuật";
                    }
                    else if (reader["Job"].ToString() == "4")
                    {
                        Job.Text = "<b>Công Việc: </b> Học Sinh, Sinh Viên";
                    }
                    else if (reader["Job"].ToString() == "5")
                    {
                        Job.Text = "<b>Công Việc: </b> Nhà Nước";
                    }
                    else if (reader["Job"].ToString() == "6")
                    {
                        Job.Text = "<b>Công Việc: </b> Nông Dân, Người Lao Động";
                    }
                    //LbJob.Text = reader["Job"].ToString();
                }
                cnn.Close();
            }
            catch (Exception ex)
            {
                Response.Write(ex);
                cnn.Close();
            }
        }
      
        protected void bt_ImportExcel_Click(object sender, EventArgs e)
        {
            Response.Redirect("../mds.ContactManagement/ImportExcel.aspx");
           
        }

        //xuất ra file excel:
        protected void bt_ExportExcel_Click(object sender, EventArgs e)
        {
            Response.Redirect("../mds.ContactManagement/ExportExcel.aspx");
            
        }

        protected void Btn_Next_Click(object sender, EventArgs e)
        {

        }

        protected void Btn_Previous_Click(object sender, EventArgs e)
        {

        } 
	 }
}
